//
//  JPEmotionTool.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 2016/10/6.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit

//  每页的表情数量
let NumberOfPage = 20
//  最近表情数组保存的沙盒路径
let RecentEmotionPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("recentEmotionArray.archiver")

class JPEmotionTool: NSObject {
    
    static let sharedEmotionTool = JPEmotionTool()
    
    private override init() {
        super.init()
    }

    //  表情所在bundle
    lazy var emoticonBundle: Bundle = {
        let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil)!
//        let bundle = Bundle.init(path: path)!
        let bundle = Bundle(path: path)
        return bundle!
    }()
    
    lazy var allEmotionArr: [[[JPEmotion]]] = {
                
        return [
            [self.recentEmotionArray],
            self.sectionEmotion(emtionArr: self.defaultEmoticonsArray),
            self.sectionEmotion(emtionArr: self.emojiEmoticonsArray),
            self.sectionEmotion(emtionArr: self.lxhEmoticonsArray),
        ]
    }()
    
    //  获取最近表情数据
    lazy var recentEmotionArray: [JPEmotion] = {
        guard let array = self.loadRecentEmotion() else {
            return [JPEmotion]()
        }
        
        return array
    }()
    
    //  获取默认表情数据
    private lazy var defaultEmoticonsArray: [JPEmotion] = {
        
        return self.loadEmotionArray(folderName: "default", fileName: "info.plist")
        
    }()
    
    //  获取emoji表情数据
    private lazy var emojiEmoticonsArray: [JPEmotion] = {
        
        return self.loadEmotionArray(folderName: "emoji", fileName: "info.plist")
        
    }()
    
    //  获取浪小花表情数据
    private lazy var lxhEmoticonsArray: [JPEmotion] = {
        
        return self.loadEmotionArray(folderName: "lxh", fileName: "info.plist")
        
    }()
    
    //  读取表情数据
    private func loadEmotionArray(folderName: String, fileName: String) -> [JPEmotion] {
        let subpath = folderName + "/" + fileName
        let path = emoticonBundle.path(forResource: subpath, ofType: nil)!
        
        let dictArr = NSArray(contentsOfFile: path) as! [[String: Any]]
        
        let modelArr = NSArray.yy_modelArray(with: JPEmotion.self, json: dictArr) as! [JPEmotion]
        
        for model in modelArr {
            if model.type == "0" {
                model.folderName = folderName
                model.path = emoticonBundle.path(forResource: folderName, ofType: nil)! + "/" + model.png!
            }
        }
        return modelArr
    }
    
    //  将表情数组拆分为二维数组
    private func sectionEmotion(emtionArr: [JPEmotion]) -> [[JPEmotion]] {
        //  本组表情需要的页数
        let numberForPage = (emtionArr.count - 1) / NumberOfPage + 1
        
        var tempArrM = [[JPEmotion]]()
        
        for i in 0..<numberForPage {
//            let range = NSRange.init(location: i * NumberOfPage, length: NumberOfPage)
            let loc = i * NumberOfPage
            var len = NumberOfPage
            if loc + len > emtionArr.count {
                len = emtionArr.count - loc
            }
            
            let subArr = (emtionArr as NSArray).subarray(with: NSMakeRange(loc, len))
            
            tempArrM.append(subArr as! [JPEmotion])
            
        }
        
        return tempArrM
    }
    
    //  保存最近表情
    func saveRecentEmotion(emotion: JPEmotion) {
        
        
        for (i,emotionModel) in recentEmotionArray.enumerated() {
            
            if emotionModel == emotion {
                recentEmotionArray.remove(at: i)
            }
        }
        recentEmotionArray.insert(emotion, at: 0)
        
        if recentEmotionArray.count > 20 {
            recentEmotionArray.removeLast()
        }
        
        allEmotionArr[0][0] = recentEmotionArray
        
        NSKeyedArchiver.archiveRootObject(recentEmotionArray, toFile: RecentEmotionPath)
    }
    
    //  查找表情描述对应的表情模型
    func seacherEmotionWithChs(chs: String) -> JPEmotion? {
        for emotion in defaultEmoticonsArray {
            if emotion.chs == chs {
                return emotion
            }
        }
        
        for emotion in lxhEmoticonsArray {
            if emotion.chs == chs {
                return emotion
            }
        }
        
        return nil
    }
    
    //  加载最近表情
    func loadRecentEmotion() -> [JPEmotion]? {
        return NSKeyedUnarchiver.unarchiveObject(withFile: RecentEmotionPath) as? [JPEmotion]
    }
}


